package eu.ec.ellipcis.integration.ws.endpoint;

import java.util.Date;
import java.util.Map;
import java.util.Random;

import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.Message;
import org.springframework.integration.MessageHeaders;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.xml.source.DomSourceFactory;
import org.springframework.stereotype.Component;

import eu.ec.ellipcis.integration.ws.policy.CustomValidationPolicy;
import eu.ec.ellipcis.integration.ws.support.CommonConfiguration;

//@Component
public class CustomValidationServiceEndpoint {

    /* ---- Constants ---- */

  private String replyTemplate =
  "<TicketResponse xmlns=\"" + CommonConfiguration.NAMESPACE + "\">" +
          "<ticket>" +
          "<description>%s</description>" +
          "<priority>%s</priority>" +
          "<ticketId>%d</ticketId>" +
          "<issueDateTime>%tc</issueDateTime>" +
          "</ticket>" +
          "</TicketResponse>";


    /* ---- Instance Variables ---- */

    @Autowired
    private Map<String, CustomValidationPolicy> customValidationPolicyMap = null;

    /* ---- Constructors ---- */

    /* ---- Business Methods ---- */

    @ServiceActivator
    public Source handleRequest(Message<?> message) throws Exception {
        MessageHeaders messageHeaders = message.getHeaders();
        String documentType = messageHeaders.get("documentType", String.class);
        (customValidationPolicyMap.get(documentType)).validate((DOMSource)message.getPayload());

        // Transfer properties to an XML document
        String xml = String.format(replyTemplate, "Dummy Description", "1",
                new Random().nextLong() * 1000, new Date());

        return new DomSourceFactory().createSource(xml);
    }


    /* ---- Getters and Setters ---- */

    public Map<String, CustomValidationPolicy> getCustomValidationPolicyMap() {
        return customValidationPolicyMap;
    }


    public void setCustomValidationPolicyMap(
            Map<String, CustomValidationPolicy> customValidationPolicyMap) {
        this.customValidationPolicyMap = customValidationPolicyMap;
    }
}

